﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Drawing.Imaging;
using RedSand.Web.Security;
using System.IO;

namespace RedSand.Web.Mvc.Controllers
{
    public class RedSandController : Controller
    {
        [AllowRedSandIndex]
        public void Index()
        {
            Response.Write("<h1 style='color:#123456;margin-bottom:0'>TRUNG TÂM PHÁT TRIỂN CÔNG NGHỆ REDSAND</h1>");
            Response.Write("<h2 style='color:#456789;margin-top:0'>Website: <a href='http://redsand.vn'>redsand.vn</a></h2>");
            Response.End();
        }
        public void CaptchaImage(string code, int? width, int? height, string fontFamily, bool? addNoise, string textColor, string backColor, string brushColor)
        {
            width = (width == null || width < 0 || width > 300) ? 150 : width;
            height = (height == null || height < 0 || height > 100) ? 30 : height;

            addNoise = addNoise ?? false;
            backColor = string.IsNullOrWhiteSpace(backColor) ? "#ffffff" : backColor;
            brushColor = string.IsNullOrWhiteSpace(brushColor) ? "#cccccc" : brushColor;
            textColor = string.IsNullOrWhiteSpace(textColor) ? "#000000" : textColor;

            try { ColorTranslator.FromHtml(backColor); }
            catch { backColor = "#ffffff"; }
            try { ColorTranslator.FromHtml(brushColor); }
            catch { brushColor = "#cccccc"; }
            try { ColorTranslator.FromHtml(textColor); }
            catch { textColor = "#000000"; }

            string text = RsEncryption.TripleDESDecrypt(RsKey.CaptchaKey, code);

            Random random = new Random();

            // Create a new 32-bit bitmap image.
            Bitmap bitmap = new Bitmap(width.Value, height.Value, PixelFormat.Format32bppArgb);

            // Create a graphics object for drawing.
            Graphics g = Graphics.FromImage(bitmap);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Rectangle rect = new Rectangle(0, 0, width.Value, height.Value);

            // Fill in the background.
            HatchBrush hatchBrush = new HatchBrush(HatchStyle.Wave, ColorTranslator.FromHtml(brushColor), ColorTranslator.FromHtml(backColor));
            g.FillRectangle(hatchBrush, rect);

            // Set up the text font.
            SizeF size;
            float fontSize = rect.Height + 1;
            Font font;
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            // Adjust the font size until the text fits within the image.
            do
            {
                fontSize--;
                font = new Font(fontFamily, fontSize, FontStyle.Bold);
                size = g.MeasureString(text, font, new SizeF(width.Value, height.Value), format);
            } while (size.Width > rect.Width);

            // Create a path using the text and warp it randomly.
            GraphicsPath path = new GraphicsPath();
            path.AddString(text, font.FontFamily, (int)font.Style, font.Size, rect, format);
            float v = 4F;
            PointF[] points =
			{
				new PointF(random.Next(rect.Width) / v, random.Next(rect.Height) / v),
				new PointF(rect.Width - random.Next(rect.Width) / v, random.Next(rect.Height) / v),
				new PointF(random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v),
				new PointF(rect.Width - random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v)
			};
            Matrix matrix = new Matrix();
            matrix.Translate(0F, 0F);
            path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

            // Draw the text.
            hatchBrush = new HatchBrush(HatchStyle.DashedUpwardDiagonal, ColorTranslator.FromHtml(brushColor), ColorTranslator.FromHtml(textColor));
            g.FillPath(hatchBrush, path);

            // Add some random noise.
            if (addNoise.Value)
            {
                int m = Math.Max(rect.Width, rect.Height);
                for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
                {
                    int x = random.Next(rect.Width);
                    int y = random.Next(rect.Height);
                    int w = random.Next(m / 50);
                    int h = random.Next(m / 50);
                    g.FillEllipse(hatchBrush, x, y, w, h);
                }
            }

            // Clean up.
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();

            Response.Clear();
            Response.ContentType = "image/jpeg";
            bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
            Response.End();
        }

    }

    public class AllowRedSandIndexAttribute : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            try
            {
                return Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["AllowViewRedSandIndexPage"]);
            }
            catch
            {
                return false;
            }
        }
    }
  
}
